import 'package:flutter/material.dart';
import '../models/product.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';


typedef ProductDetailCallBack = void Function(Map action);

class ProductDetail extends StatefulWidget {
  final Product product;
  final ProductDetailCallBack callBack;
  ProductDetail(this.product,this.callBack);
  @override
  _ProductDetailState createState() => _ProductDetailState();
}

class _ProductDetailState extends State<ProductDetail> {
  //定义一个与原生之间的通信通道
  static const platform =
  const MethodChannel('com.flutter.guide.MyFlutterView');

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    platform.setMethodCallHandler((call){
      print('app端调用');
      print(call.method);
      print(call.arguments);

      //返回给app端
      Future<Map> future = new Future(() => {"name":"李四","age":20});
      return future;
    });
    //调用原生app方法
    if (defaultTargetPlatform == TargetPlatform.iOS){
      //安卓还没哟实现这个方法
      platform
          .invokeMethod('callNative', {'action': 'closeFlutter', 'data': {}}).then((value){
        print('返回数据');
        print(value);
      });
    }
  }

  //渲染原生的view
  Widget platformView(){
    if (defaultTargetPlatform == TargetPlatform.android) {
//      return AndroidView(
//        viewType: 'plugins.flutter.io/custom_platform_view',
//        creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
//        creationParamsCodec: StandardMessageCodec(),
//      );
      //这里没有实现安卓
      return Container();
    } else if (defaultTargetPlatform == TargetPlatform.iOS) {
      return UiKitView(
        viewType: 'plugins.flutter.io/custom_platform_view',
        creationParams: {'text': '这是原生view'},
        creationParamsCodec: StandardMessageCodec(),
      );
    } else {
      return Container();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("商品详情"),),
      body: Center(
        child: Column(
          children: [
            Text(widget.product.name),
            Text(widget.product.price.toString()),
            Image.network(widget.product.imageURL,width: 100,height: 50,),
            SizedBox(height: 20,),
            Image.asset("lib/resource/imgs/miku.png",width: 100,height: 100,),
            ElevatedButton(onPressed: (){
              this.widget.callBack({"msg":"你好啊"});
            }, child: Text('通知上层变化')),
            Container(
              width: 200,
              height: 100,
              child: platformView(),
            ),
            ElevatedButton(onPressed: (){
              Navigator.pop(context);
            }, child: Text('返回'))
          ],
        ),
      ),
    );
  }
}
